<template>
    <el-dialog class="material-dialog" :title="style=='self'?'我的文件资源库':'公共资源库'" :visible.sync="visible" width="800px" :close-on-click-modal="false" :modal-append-to-body="true" :modal="true" :append-to-body="true">
        <el-container style="height:400px">
            <el-aside width="200px" style="padding: 0px; height: 100%;display: grid;" v-loading="loading.tLoading" element-loading-text="正在获取" v-if="style=='self'">
                <!-- <tree-ui ref="tree" class="h-100" :data="tree.list" :props="{key:'id'}" @node-click="_onNodeClick"></tree-ui> -->
            </el-aside>
            <el-main style="padding: 10px;" v-loading="loading.cLoading" element-loading-text="正在获取文件">
                <el-container class="h-100">
                    <el-main style="padding: 0px;height:h-100;overflow:auto">
                        <div class="null-content" style="padding-top:20px !important" v-if="fileInfo.list.length < 1">
                            <el-image :src="require('@img/null-data.png')"></el-image>
                            <div>暂无内容...</div>
                        </div>
                        <list-ui v-else :list="fileInfo.list" :props="{ xs: 6, sm: 6, md: 6, lg: 6, xl:6 }" @node-click="_onItemClick">
                            <template slot-scope="{data}">
                                <!-- v-if="isResoucre && (data.fileDetailsInfo && TYPE.includes(data.fileDetailsInfo.fileSuffix))" -->
                                <material-item :data="data" @on-change="_onChange" v-bind="$attrs"></material-item>
                            </template>
                        </list-ui>

                    </el-main>
                    <el-footer class="page-box">
                        <el-pagination background small layout="prev, pager, next" :current-page.sync="fileInfo.page.pageIndex" :total="fileInfo.page.total" :page-size="fileInfo.page.pageSize" @current-change="_onPageChange">
                        </el-pagination>
                    </el-footer>
                </el-container>
            </el-main>
        </el-container>
        <span slot="footer">
            <el-button size="medium" @click="visible = false">取 消</el-button>
            <el-button size="medium" type="primary" @click="_onSubmitClick">确 定</el-button>
        </span>
        <!-- 裁剪图片 -->
        <crop-pic ref="CropPicUI" :cropInfo="cropInfo"></crop-pic>
    </el-dialog>
</template>

<script>
// import TreeUI from '@public/tree-ui';
// import $resourceAPI from '@api1.0/resource-tool';
import FILE from '@utils/file';
import MaterialItem from './material-item';
import CropPic from './crop-pic';
const TYPE = ['xlsx', 'xls', 'txt', 'csv', 'xml', 'json'];
/**
 * 当前组件为资源选择类型的窗口
 * 
 * 对外提供
 * 
 * 方法：
 * init(type) -> 初始化
 * 
 */

export default {
    name: 'material-dialog',
    components: {
        // [TreeUI.name]: TreeUI,
        [MaterialItem.name]: MaterialItem,
        [CropPic.name]: CropPic
    },
    props: {
        //是否裁剪图片
        isCrop: { type: Boolean, default: false },
        //裁剪信息
        cropInfo: {
            type: Object, default() {
                return {
                    autoCropWidth: 200,//裁剪框的宽度
                    autoCropHeight: 200,//裁剪框的高度
                    enlarge: 1,//裁剪出来的图片是裁剪框的倍数
                }
            }
        },
        multiple: { type: Boolean, default: false },//多文件选择
    },
    data() {
        return {
            TYPE,
            userType: (this.$user.read() || {}).type,//用户身份类型
            tree: {
                list: [],
                selected: undefined,
            },
            loading: {
                tLoading: false,
                cLoading: false
            },
            fileInfo: {
                list: [],
                dirNum: 0,
                fileNum: 0,
                page: {
                    total: 0,
                    pageSize: 50,
                    pageIndex: 1
                }
            }, // 文件信息
            type: {
                dirType: "file",			//file:文件类；mind：思维图谱类；project：项目类；dataset：数据集类；chart：图表类
                fileType: "image",			//此类型与dirType相关 FileTypeEnum
                isShowDir: false,				//是否展示文件夹
            },
            style: "self",	//self 个人资源 public 公共资源
            visible: false,
            resolve: false,
            reject: false,
        }
    },
    methods: {
        /**
         * 初始化弹窗,并设置弹窗文件类型
         */
        init(type, style = 'self') {
            this.style = style
            this.type = type;
            this.fileInfo.list = []
            return this._show();
        },
        _onSubmitClick() {
            //多文件选择
            if (this.multiple) {
                let selectList = this.fileInfo.list.filter(item => { return item.selected })
                if (selectList.length == 0) return this.$notify.warning("请选择文件")
                this.resolve && this.resolve(selectList)
                this.visible = false;
                this.resolve = undefined;
                this.reject = undefined;
                return
            }
            //单文件选择
            let target = this.fileInfo.list.find(item => { return item.selected == true; })
            if (!target) return this.$notify.warning('请选择文件');
            let { id, title, fileUUID, coverUUID, fileDetailsInfo, rootId, rootCategory, rootType, previewUUID, name } = target;
            let url = FILE.cover(fileUUID, 'material')
            if (this.isCrop) {
                this.$refs.CropPicUI.show(url, target).then(res => {
                    this.resolve && this.resolve({ id, title, fileUUID, fileDetailsInfo, rootId, rootCategory, rootType, coverUUID, previewUUID, name, file: res });
                    this.visible = false;
                    this.resolve = undefined;
                    this.reject = undefined;
                }).catch(() => { })
            } else {
                this.resolve && this.resolve({ id, title, fileUUID, fileDetailsInfo, rootId, rootType, rootCategory, coverUUID, previewUUID, name });
                this.visible = false;
                this.resolve = undefined;
                this.reject = undefined;
            }
        },

        // 点击树节点
        _onNodeClick(data) {
            // console.log("==============点击树节点：：：", data);
            this.tree.selected = data;
            this._onLibrarySoruce();
        },

        // 获取文件夹相关的文件
        _onLibrarySoruce() {
            this.loading.cLoading = true;
            let { pageIndex, pageSize } = this.fileInfo.page;
            function _parse(list, fileType) {
                return new Promise((resolve) => {
                    if (!list || !list.length) return resolve([]);
                    resolve(list.map(item => {
                        let { fileDetailsInfo, id, rootId, title, rootType } = item;
                        if (rootType != 'file' && !fileDetailsInfo) {
                            return { id, title, rootType, isCheckbox: true }
                        }
                        if (!fileDetailsInfo) {
                            return { id, title, rootType, isCheckbox: false }
                        }
                        (fileDetailsInfo || {}).isCheckbox = fileType != 'dir';
                        (fileDetailsInfo || {}).isCheckbox = (fileDetailsInfo || {}).previewUUID
                        fileDetailsInfo.selected = false;
                        fileDetailsInfo.id = id
                        fileDetailsInfo.rootId = rootId
                        fileDetailsInfo.rootType = rootType
                        fileDetailsInfo.title = title
                        fileDetailsInfo.fileDetailsInfo = item.fileDetailsInfo
                        fileDetailsInfo.rootCategory = item.rootCategory
                        return fileDetailsInfo || {};
                    }).filter(item => item != undefined))
                })
            }
            let { dirType } = this.type
            // let isShowDir = false
            let classly = ''
            // console.log("============请求数据类型是：：", dirType);
            let fileType = '';
            switch (dirType) {
                //文件类
                case 'file':
                    // $resourceAPI.getUserFileList(this.tree.selected.id, undefined, this.type.fileType, pageIndex, pageSize, isShowDir).then(res => {
                    //     this.loading.cLoading = false;
                    //     let { dirs, list, page } = res || {};
                    //     _parse(dirs, 'dir').then((dirArr) => {
                    //         _parse(list).then((fileArr) => {
                    //             console.log(fileArr);
                    //             this.fileInfo = {
                    //                 dirNum: dirs.length,
                    //                 fileNum: list.length,
                    //                 list: dirArr.concat(fileArr),
                    //                 page
                    //             }
                    //             // if (this.tree.selected.parentId == this.rootId && (this.tree.selected.children && this.tree.selected.children.length != dirArr.length)) {
                    //             //     this._getLibraryList();
                    //             // }
                    //         }).catch(() => { });
                    //     }).catch(() => { });
                    // }).catch(() => {
                    //     this.loading.cLoading = false;
                    // })
                    break;
                //图谱类的
                case 'mind':
                    this.loading.cLoading = true;
                    this.type.fileType == 'tree' ? fileType = 'decisionMaking' : fileType = this.type.fileType;
                    $resourceAPI.getUserAtlasList(undefined, this.type.fileType == 'all' ? undefined : fileType, pageIndex, undefined, this.tree.selected.id).then(res => {
                        this.loading.cLoading = false;
                        let { dirs, list, page } = res || {};
                        _parse(dirs, 'dir').then(() => {
                            _parse(list).then((fileArr) => {
                                this.fileInfo = {
                                    dirNum: dirs.length,
                                    fileNum: list.length,
                                    list: fileArr,
                                    page
                                }
                                // if (this.rootId && this.tree.selected.parentId == this.rootId && (this.tree.selected.children && this.tree.selected.children.length != dirArr.length)) {
                                //     this._getLibraryList();
                                // }
                            }).catch(() => { });
                        }).catch(() => { });
                    }).catch(() => {
                        this.loading.cLoading = false;
                    })
                    break;

                case 'project':
                    if (this.type.fileType == 'panorama') {
                        classly = 'panoramaProject'
                    } else if (this.type.fileType == 'h5') {
                        classly = 'htmlProject'
                    } else if (this.type.fileType == 'video') {
                        classly = 'mediaProject'
                    } else {
                        classly = undefined
                    }
                    $resourceAPI.getUserProjectList(undefined, classly, pageIndex, undefined, this.tree.selected.id).then(res => {
                        this.loading.cLoading = false;
                        let { dirs, list, page } = res || {};
                        _parse(dirs, 'dir').then(() => {
                            _parse(list).then((fileArr) => {
                                this.fileInfo = {
                                    dirNum: dirs.length,
                                    fileNum: list.length,
                                    list: fileArr,
                                    page
                                }
                                // if (this.rootId && this.tree.selected.parentId == this.rootId && (this.tree.selected.children && this.tree.selected.children.length != dirArr.length)) {
                                //     this._getLibraryList();
                                // }
                            }).catch(() => { });
                        }).catch(() => { });
                    }).catch(() => {
                        this.loading.cLoading = false;
                    })
                    break;
                case 'dataset':
                    $resourceAPI.queryDatabasePersonSearch(undefined, pageIndex, pageSize, this.tree.selected.id, true).then(res => {
                        this.loading.cLoading = false;
                        let { dirs, list, page } = res || {};
                        console.log(dirs, list);
                        _parse(dirs, 'dir').then(() => {
                            _parse(list).then((fileArr) => {
                                this.fileInfo = {
                                    dirNum: dirs.length,
                                    fileNum: list.length,
                                    list: fileArr,
                                    page
                                }
                            }).catch(() => { });
                        }).catch(() => { });
                    }).catch(() => {
                        this.loading.cLoading = false;
                    })
                    break;
                case 'chart':
                    $resourceAPI.getChartPerson({ pageIndex, pageSize, showDir: true, dirId: this.tree.selected.id }).then(res => {
                        this.loading.cLoading = false;
                        let { dirs, list, page } = res || {};
                        _parse(dirs, 'dir').then(() => {
                            _parse(list).then((fileArr) => {
                                this.fileInfo = {
                                    dirNum: dirs.length,
                                    fileNum: list.length,
                                    list: fileArr,
                                    page
                                }
                            }).catch(() => { });
                        }).catch(() => { });
                    }).catch(() => {
                        this.loading.cLoading = false;
                    })
                    break;
                case 'dashboard':
                    $resourceAPI.searchDashboard({ pageIndex, pageSize, showDir: true, dirId: this.tree.selected.id }).then(res => {
                        this.loading.cLoading = false;
                        let { dirs, list, page } = res || {};
                        _parse(dirs, 'dir').then(() => {
                            _parse(list).then((fileArr) => {
                                this.fileInfo = {
                                    dirNum: dirs.length,
                                    fileNum: list.length,
                                    list: fileArr,
                                    page
                                }
                            }).catch(() => { });
                        }).catch(() => { });
                    }).catch(() => {
                        this.loading.cLoading = false;
                    })
                    break;
                default:
                    this.loading.cLoading = false;
                    console.log("===========是什么类型：：", dirType);
                    break
            }
        },

        //处理树
        _onTreeTool(list) {
            list = list.map(item => {
                let { id, child, title, parentId } = item
                let children = [];
                if (parentId == 0) {
                    this.rootId = id
                }
                if (child && child.length) {
                    children = this._onTreeTool(child)
                }
                return { id, key: id, label: title, parentId, children, icon: 'el-icon-folder' };
            })
            return list
        },

        // 获取全部文件夹
        _getLibraryList() {
            this.loading.tLoading = true;
            let { dirType } = this.type;
            $resourceAPI.getDirTree({ type: dirType, parentId: 0 }).then(res => {
                this.loading.tLoading = false;
                let treeData = [{
                    id: 0,
                    key: 0,
                    label: "全部资源",
                    icon: "el-icon-folder",
                    children: this._onTreeTool(res || [])
                }];
                this.tree.list = treeData;
            }).catch(() => {
                this.loading.tLoading = false;
            })
        },
        _onChange(data) {
            this.fileInfo.list = (this.fileInfo.list || []).map(item => {
                // 单选
                if (!this.multiple) {
                    item.selected = false;
                    if (item.id == data.id) {
                        item.selected = true;
                    }
                }
                return item;
            })
        },
        // 点击文件夹
        _onItemClick(data) {
            let { item } = data;
            if (item.type != 'dir') return;
            this.$refs.tree.setCurrentKey(data.item);
        },

        // 分页查询
        _onPageChange(index) {
            this.fileInfo.page.pageIndex = index;
            this._onLibrarySoruce();
        },
        // 查询公开资源
        _getPubFileList() {
            let { pageIndex, pageSize } = this.fileInfo.page;
            const { fileType } = this.type
            $resourceAPI.getPubFileList(undefined, fileType, pageIndex, pageSize).then(res => {
                let { list } = res;
                this.fileInfo.list = [];
                (list || []).forEach(element => {
                    let { fileDetailsInfo } = element;
                    if (fileDetailsInfo != undefined) {
                        let { coverUUID, fileSuffix, fileType, fileUUID } = fileDetailsInfo;
                        element.coverUUID = coverUUID;
                        element.fileSuffix = fileSuffix;
                        element.fileType = fileType;
                        element.isCheckbox = fileUUID;
                        element.previewUUID = fileUUID;
                        element.fileUUID = fileUUID;
                        element.selected = false;
                    }
                    this.fileInfo.list.push(element);
                });

                // this.fileInfo.list = list
                this.fileInfo.page = res.page
            })
        },
        // 查询管理员的资料
        _getAdminFileList() {
            let { pageIndex, pageSize } = this.fileInfo.page;
            const { fileType } = this.type
            $resourceAPI.getLibFileList(undefined, fileType, pageIndex, pageSize).then(res => {
                let { list } = res;
                this.fileInfo.list = [];
                (list || []).forEach(element => {
                    let { fileDetailsInfo } = element;
                    if (fileDetailsInfo != undefined) {
                        let { coverUUID, fileSuffix, fileType, fileUUID } = fileDetailsInfo;
                        element.coverUUID = coverUUID;
                        element.fileSuffix = fileSuffix;
                        element.fileType = fileType;
                        element.isCheckbox = fileUUID;
                        element.previewUUID = fileUUID;
                        element.fileUUID = fileUUID;
                        element.selected = false;
                    }
                    this.fileInfo.list.push(element);
                });

                // this.fileInfo.list = list
                this.fileInfo.page = res.page
            })
        },
        _show() {
            this.visible = true;
            if (this.userType == 'eduAdmin') {
                this._getAdminFileList();
                return new Promise((resolve, reject) => {
                    this.resolve = resolve;
                    this.reject = reject;
                })
            }
            if (this.style == 'public') {
                this._getPubFileList() //如果pulibc 那么查看公开资源	否则查看个人资源
            }
            else {
                this._getLibraryList();
            }
            // 公开的资源库
            return new Promise((resolve, reject) => {
                this.resolve = resolve;
                this.reject = reject;
            })
        },
    }
}
</script>
<style lang="scss" scoped>
.material-dialog {
    /deep/.el-dialog .el-dialog__body {
        padding: 0px;
    }
}
</style>